package com.emagic.manage.data.datasource;

import android.content.Context;

import com.emagic.manage.data.cache.ICache;
import com.emagic.manage.data.utils.Preconditions;

import javax.inject.Inject;
import javax.inject.Singleton;

import timber.log.Timber;

/**
 * TODO 描述该文件做什么
 *
 * @author baoy
 * @version 1.0
 *          Create by 16/1/8 下午12:30
 */
@Singleton
public class DataSourceFactory {

    private final Context mContext;


    private RestDataSource restDataSource;

    private DBDataSource dbDataSource;

    private CacheDataSource cacheDataSource;


    @Inject
    public DataSourceFactory(Context context, RestDataSource restDataSource,
                             DBDataSource dbDataSource, CacheDataSource cacheDataSource) {

        if (context == null) {
            throw new IllegalArgumentException("Constructor parameters cannot be null!!!");
        }
        this.mContext = context;
        this.restDataSource = restDataSource;
        this.dbDataSource = dbDataSource;
        this.cacheDataSource = cacheDataSource;
    }


    public DataSource createRestDataSource() {
        return restDataSource;
    }

    public DataSource createDBDataSource() {
        return dbDataSource;
    }

    public DataSource createCacheDataSource() {
        return cacheDataSource;
    }

    public DataSource createDataSource(String key, ICache<?> cache) {

        DataSource dataSource;

        Preconditions.checkNotNull(key, "key parameter cannot be null");
        Preconditions.checkNotNull(cache, "cache parameter cannot be null");


        if (cache.isCached(key) && !cache.isExpired(key)) {
            cacheDataSource.putCache(key, cache);
            dataSource = cacheDataSource;
            Timber.v("CacheDataSource has been created...");
        } else {
            restDataSource.putCache(key, cache);
            dataSource = restDataSource;
            Timber.v("RestDataSource has been created...");
        }

        return dataSource;
    }
}
